package com.zhuoyue.elmt.web;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.utils.IdGen;
import com.eit.eitsite.common.utils.StringUtils;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.modules.sys.entity.User;
import com.eit.eitsite.modules.sys.security.SystemAuthorizingRealm;
import com.eit.eitsite.modules.sys.service.SystemService;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.zhuoyue.elmt.UserExtUtils;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.MaintenanceRecordSz;
import com.zhuoyue.elmt.entity.MaintenanceStaff;
import com.zhuoyue.elmt.entity.UserExt;
import com.zhuoyue.elmt.service.MaintenanceStaffService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = "${adminPath}/elmt/userext")
public class UserExtController extends BaseController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private MaintenanceStaffService maintenanceStaffService;

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
        ResultData<List<UserExt>> resultData = new ResultData();
        List<UserExt> fileList = new ArrayList();
        resultData.setCode("SUCC");
        resultData.setMessage("头像上传成功");
        SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal) UserUtils.getPrincipal();
        if (!file.isEmpty()) {
            String relaPath = Global.USERFILES_BASE_URL + principal + "/" + "images/";
            String realPath = Global.getUserfilesBaseDir() + relaPath;
            String fileName = file.getOriginalFilename();
            String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
            File targetFile = new File(realPath, rname);
            // 目录不存在，则创建目录
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 保存
            try {
                file.transferTo(targetFile);
                String filePath = request.getContextPath() + relaPath + rname;
                User user = UserUtils.getUser();
                UserUtils.updateUserPhoto(user.getId(), filePath);

                UserExt userExt = new UserExt();
                userExt.setPhoto(filePath);

                fileList.add(userExt);
            } catch (Exception e) {
                resultData.setCode("FAIL");
                resultData.setMessage("头像上传失败");
                e.printStackTrace();
            }
        } else {
            resultData.setCode("FAIL");
            resultData.setMessage("头像上传失败");
        }
        resultData.setList(fileList);
        return super.renderString(response, resultData);
    }

    @RequestMapping(value = "logout")
    public String logout(HttpServletResponse response, HttpServletRequest request) {
        // 移除登录
        systemService.getSessionDao().delete(UserUtils.getSession());

        ResultData<List<UserExt>> resultData = new ResultData();
        resultData.setCode("SUCC");
        resultData.setMessage("退出登录成功");
        try {
            // 移除登录
            systemService.getSessionDao().delete(UserUtils.getSession());
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("退出登录异常");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(value = "info")
    public String info(User user, HttpServletResponse response, HttpServletRequest request, Model model, String certificateNo) {
        ResultData<List<UserExt>> resultData = new ResultData();
        List<UserExt> userList = new ArrayList();
        User currentUser = UserUtils.getUser();
        resultData.setCode("SUCC");
        resultData.setMessage("用户信息更新成功");
        try {
            UserExt userExt = new UserExt();

            if (StringUtils.isNotBlank(user.getName())) {
                currentUser.setName(user.getName());
                systemService.updateUserInfo(currentUser);
            }
            if (StringUtils.isNotBlank(user.getName()) || StringUtils.isNotBlank(certificateNo)) {
                MaintenanceStaff maintenanceStaff = maintenanceStaffService.getByLoginName(currentUser.getLoginName());
                if (StringUtils.isNotBlank(user.getName())) {
                    maintenanceStaff.setStaffName(user.getName());
                }
                if (StringUtils.isNotBlank(certificateNo)) {
                    maintenanceStaff.setCertificateNo(certificateNo);
                }
                maintenanceStaffService.update(maintenanceStaff);

                userExt.setCertificateNo(maintenanceStaff.getCertificateNo());

            }
            userExt.setId(currentUser.getId());
            userExt.setPhoto(currentUser.getPhoto());
            userExt.setName(currentUser.getName());
            userExt.setLoginName(currentUser.getLoginName());

            // 累计故障次数 评分
            userExt.setFailureNum(UserExtUtils.statFailureReport(currentUser.getLoginName()));
            userExt.setScore(UserExtUtils.getScore(currentUser.getLoginName()));

            userList.add(userExt);
            resultData.setList(userList);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("用户信息更新异常");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(value = "updatePush")
    public String updatePush(User user, String regpushid, HttpServletResponse response, HttpServletRequest request, Model model, String certificateNo) {
        ResultData resultData = new ResultData();
        User currentUser = UserUtils.getUser();
        resultData.setCode("SUCC");
        resultData.setMessage("更新推送设备号成功");
        try {
            MaintenanceStaff maintenanceStaff = maintenanceStaffService.getByLoginName(currentUser.getLoginName());
            if (StringUtils.isEmpty(maintenanceStaff.getRegpushid())) {
                maintenanceStaff.setRegpushid(regpushid);
                maintenanceStaffService.update(maintenanceStaff);
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("用户信息更新异常");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(HttpServletResponse response, HttpServletRequest request, String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        ResultData<UserExt> resultData = new ResultData();
        resultData.setCode("SUCC");
        resultData.setMessage("用户密码更新成功");
        try {
            if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
                if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                    systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                } else {
                    resultData.setCode("FAIL");
                    resultData.setMessage("修改密码失败，旧密码错误");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("旧密码和新密码不能为空");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("用户密码更新异常");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }
}
